package com.hspedu.qqserver.service;

import com.hspedu.qqcommon.Message;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/3/21
 * @time 14:47
 */
public class SendOfflineMessageService implements Runnable{
    /**
     * String 是目标用户id
     * Message 是离线发送的消息
     */
    private static volatile ConcurrentHashMap<String, ArrayList<Message>> offlineMessage =
            new ConcurrentHashMap<>();
    @Override
    public void run() {
        while (true){
            if (offlineMessage.size() != 0){
                //说明此时有离线消息需要发送
                for (String targetUserId : offlineMessage.keySet()) {
                    HashMap<String, ServerConnectClientThread> allServerThreads =
                            ManageServerConnectClientThread.getAllServerThreads();
                    ServerConnectClientThread targetUserThread;
                    //判断该用户此时是否在线，如果在线则有相应的线程存在
                    if ((targetUserThread = allServerThreads.get(targetUserId)) != null){
                        //说明此时该用户在线，向该用户发送消息
                        //获取该用户所有离线信息，循环发送
                        ArrayList<Message> messages = offlineMessage.get(targetUserId);
                        Socket socket = targetUserThread.getSocket();
                        while (messages.size() != 0) {
                            for (Message message : messages) {
                                try {
                                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                                    oos.writeObject(message);
                                    oos.flush();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            messages.clear();
                            offlineMessage.remove(targetUserId);
                        }
                    }
                }
            }
        }
    }

    public static ConcurrentHashMap<String, ArrayList<Message>> getOfflineMessage() {
        return offlineMessage;
    }

    public static void setOfflineMessage(String targetUserId, Message message){
        ArrayList<Message> messages = offlineMessage.get(targetUserId);
        if (messages == null){
            //说明是第一次接收离线消息
            messages = new ArrayList<>();
            messages.add(message);
        }else{
            messages.add(message);
        }
        offlineMessage.put(targetUserId,messages);
    }
}
